/*
 * Copyright (C) 2017 Gautam Chibde
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.chibde.visualizer;

import com.chibde.BaseVisualizer;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.LinearShader;
import ohos.agp.render.Paint;
import ohos.agp.render.Shader;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.app.Context;

public class BlazingColorVisualizer extends BaseVisualizer implements Component.DrawTask {
    private Shader shader;

    /**
     * constructor
     *
     * @param context context
     */
    public BlazingColorVisualizer(Context context) {
        super(context);
        addDrawTask(this);
    }

    /**
     * constructor
     *
     * @param context context
     * @param attrs attrs
     */
    public BlazingColorVisualizer(Context context, AttrSet attrs) {
        super(context, attrs);
        addDrawTask(this);
    }

    /**
     * constructor
     *
     * @param context context
     * @param attrs attrs
     * @param defStyleAttr defStyleAttr
     */
    public BlazingColorVisualizer(Context context, AttrSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        addDrawTask(this);
    }

    @Override
    protected void init() {
        Point[] point = new Point[]{new Point(0, 0)};
        float[] point1 = {0, getHeight()};

        Color[] colors = {Color.BLUE, Color.GREEN};
        shader = new LinearShader(point, point1, colors, Shader.TileMode.MIRROR_TILEMODE);
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        if (bytes != null) {
            paint.setShader(shader, Paint.ShaderType.LINEAR_SHADER);
            for (int i = 0, k = 0; i < (bytes.length - 1) && k < bytes.length; i++, k++) {
                int top = getHeight() + ((byte) (Math.abs(bytes[k]) + 128)) * getHeight() / 128;
                Point points = new Point(i, getHeight());
                Point pointss = new Point(i, top);
                canvas.drawLine(points, pointss, paint);
            }
        }
    }
}
